<style lang="less">
    @import "../../styles/common.less";
</style>

<template>
    <div>
        <Row type="flex" justify="space-between">
            <Row>
            </Row>
            <Row>
                <Button icon="ios-plus-outline" type="primary" @click="showAddAccountModal">新建</Button>
            </Row>
        </Row>
        <Table class="margin-top-10" ref="accountTable" :columns="accountColumn" :data="accountData"></Table>
        <!--新增账号 -->
        <Modal v-model="addAccountModal" title="添加账号" class-name="vertical-center-modal"
               @on-cancel="hideAddAccountModal">
            <Form ref="addAccountInfoForm" :model="accountInfo.add" :label-width="75" label-position="right"
                  :rules="accountInfoRule.add">
                <FormItem label="用户类型" prop="acc_role">
                    <Select v-model="accountInfo.add.acc_role">
                        <Option value="2">人事(用户管理、考勤管理)</Option>
                        <Option value="3">运营(用户管理、考勤管理、历史记录)</Option>
                    </Select>
                </FormItem>
                <FormItem label="账号" prop="acc_id">
                    <Input v-model.trim="accountInfo.add.acc_id" placeholder="请填写账号"/>
                </FormItem>
                <FormItem label="姓名" prop="acc_name">
                    <Input v-model.trim="accountInfo.add.acc_name" placeholder="请填写姓名"/>
                </FormItem>
                <FormItem label="邮箱" prop="acc_email">
                    <AutoComplete
                            v-model.trim="accountInfo.add.acc_email"
                            @on-search="handleSearch"
                            placeholder="请输入邮箱">
                        <Option v-for="item in emailList" :value="item" :key="item">{{ item }}</Option>
                    </AutoComplete>
                </FormItem>
                <FormItem label="密码" prop="acc_pwd">
                    <Input v-model.trim="accountInfo.add.acc_pwd" placeholder="请填写密码" type="password"/>
                </FormItem>
                <FormItem label="密码确认" prop="acc_pwd_check">
                    <Input v-model.trim="acc_pwd_check" placeholder="请确认密码" type="password"/>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="primary" @click="handleAddSubmit">提交</Button>
            </div>
        </Modal>
        <!--更新账号-->
        <Modal v-model="updateAccountModal" title="修改账号" class-name="vertical-center-modal"
            @on-cancel="hideUpdateAccountModal">
            <Form ref="updateAccountInfoForm" :model="accountInfo.update" :label-width="75" label-position="right"
                  :rules="accountInfoRule.update">
                <FormItem label="用户类型" prop="acc_role">
                    <Select v-model="accountInfo.update.acc_role">
                        <Option value="2">人事(用户管理、考勤管理)</Option>
                        <Option value="3">运营(用户管理、考勤管理、历史记录)</Option>
                    </Select>
                </FormItem>
                <FormItem label="账号" prop="acc_id">
                    <Input v-model="accountInfo.update.acc_id" placeholder="请填写账号"
                           disabled/>
                </FormItem>
                <FormItem label="姓名" prop="acc_name">
                    <Input v-model.trim="accountInfo.update.acc_name" placeholder="请填写姓名"/>
                </FormItem>
                <FormItem label="邮箱" prop="acc_email">
                    <AutoComplete
                            v-model.trim="accountInfo.update.acc_email"
                            @on-search="handleSearch"
                            placeholder="请输入邮箱">
                        <Option v-for="item in emailList" :value="item" :key="item">{{ item }}</Option>
                    </AutoComplete>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="primary" @click="handleUpdateSubmit">提交</Button>
            </div>
        </Modal>
        <!--重置密码-->
        <Modal v-model="resetPwdModal" :title="resetPwdModalTitleComputed" class-name="vertical-center-modal"
               @on-cancel="hideResetPwdModal">
            <Form ref="resetPwdForm" :model="accountInfo.resetPwd" :label-width="75" label-position="right"
                  :rules="accountInfoRule.resetPwd">
                <FormItem label="重置密码" prop="acc_pwd">
                    <Input v-model="accountInfo.resetPwd.user_pwd" placeholder="请输入新密码" type="password"/>
                </FormItem>
                <FormItem label="密码确认" prop="acc_pwd_check">
                    <Input v-model="acc_pwd_check" placeholder="请再次确认密码" type="password"/>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="primary" @click="handleResetSubmit">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>

    import ME from "../../controllers/accountSetting"
    import iconEdit from "../../images/edit.png"
    import iconPwd from "../../images/password.png"
    import iconDelete from "../../images/delete.png"
    import Modal from "../../../node_modules/iview/src/components/modal/modal.vue";
    import Utils from "@/libs/util"
    import MD5 from "../../libs/md5.min"
    import Constants from "../../libs/constants"
    import DateUtils from '../../../node_modules/iview/src/utils/date'
    import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip"
    import Btn from "../../../node_modules/iview/src/components/button/button"

    export default {
        components: {
            Modal,
            Tooltip,
            Btn
        },
        data() {
            const validatePwd = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.acc_pwd_check !== '') {
                        // 对第二个密码框单独验证
                        this.$refs['addAccountInfoForm'].validateField('acc_pwd_check');
                    }
                    callback();
                }
            };
            const validatePwd2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.acc_pwd_check !== '') {
                        // 对第二个密码框单独验证
                        this.$refs['resetPwdForm'].validateField('acc_pwd_check');
                    }
                    callback();
                }
            };
            const validatePwdCheck = (rule, value, callback) => {
                value = this.acc_pwd_check
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.accountInfo.add.acc_pwd) {
                    callback(new Error('密码不一致'));
                } else {
                    callback();
                }
            };
            const validatePwdCheck2 = (rule, value, callback) => {
                value = this.acc_pwd_check
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.accountInfo.resetPwd.user_pwd) {
                    callback(new Error('密码不一致'));
                } else {
                    callback();
                }
            };
            return {
                accountColumn: [
                    {
                        title: '用户名',
                        key: 'acc_name',
                        // width: '10%',
                        align: 'center'
                    },
                    {
                        title: '账号',
                        key: 'acc_id',
                        align: 'center'
                    },
                    {
                        title: '邮箱',
                        key: 'acc_email',
                        align: 'center'
                    },
                    {
                        title: '账号权限',
                        key: 'acc_role',
                        align: 'center',
                        render:(h,{row,column,index})=>{
                            let value = row[column.key]
                            let result=""
                            switch (value){
                                case 2:
                                    result="人事"
                                    break;
                                case 3:
                                    result="运营"
                                    break;
                                case 1:
                                    result="管理员"
                                    break;
                                default:
                                    break;
                            }
                            return <span>{result}</span>
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        render: (h, {row, column, index}) => {
                            let buttonSpace = '10px'
                            return (
                                <div class="operation">
                                    <Tooltip content="编辑" placement="bottom">
                                        <Btn style={{background: `url( ${iconEdit})`}} onClick={() => this.showUpdateAccountModal(row)}/>
                                    </Tooltip>
                                    <Tooltip content="重置密码" placement="bottom">
                                        <Btn style={{background: `url( ${iconPwd})`}} onClick={() => this.showResetPwdModal(row)}/>
                                    </Tooltip>
                                    <Tooltip content="删除" placement="bottom">
                                        <Btn style={{background: `url( ${iconDelete})`}} onClick={() => this.deleteAccount(row)}/>
                                    </Tooltip>
                                </div>
                            )
                        }
                    }
                ],
                accountData: [],
                addAccountModal: false,
                updateAccountModal:false,
                resetPwdModal:false,
                accountInfoRule: {
                    add:{
                        acc_role: [{required: true, message: '请选择账户类型', trigger: 'change'}],
                        acc_id: {required: true, message: '请输入账号', trigger: 'blur'},
                        acc_name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
                        acc_email: [
                            {required: true, message: '请输入邮箱账号', trigger: 'blur'},
                            {type: 'email', message: '邮箱格式不正确', trigger: 'change'},
                        ],
                        acc_pwd: [{required: true, validator: validatePwd, trigger: 'blur'}],
                        acc_pwd_check: [{required: true, validator: validatePwdCheck, trigger: 'blur'}]
                    },
                    update:{
                        acc_role: [{required: true, message: '请选择账户类型', trigger: 'blur'}],
                        acc_id: {required: true, message: '请输入账号', trigger: 'blur'},
                        acc_name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
                        acc_email: [
                            {type: 'email', message: '邮箱格式不正确', trigger: 'change'},
                        ],
                    },
                    resetPwd:{
                        acc_pwd: [{required: true, validator: validatePwd2, trigger: 'blur'}],
                        acc_pwd_check: [{required: true, validator: validatePwdCheck2, trigger: 'blur'}]
                    }
                  },
                edit_flag: false,
                accountInfo: {
                    add:{
                        acc_role: "",
                        acc_id: "",
                        acc_name: "",
                        acc_email: "",
                        acc_pwd: "",
                    },
                    update:{
                        acc_role: "",
                        acc_id: "",
                        acc_name: "",
                        acc_email: "",
                    },
                    resetPwd:{
                        user_acc:"",
                        user_pwd:""
                    }
                },
                acc_pwd_check: "",
                emailList: [],
                resetPwdTitle:""
            }
        },
        mounted(){
            this.loadTableData()
        },
        computed:{
            resetPwdModalTitleComputed:function () {
                return "重置【" + this.resetPwdTitle + "】密码"
            }
        },
        methods: {
            handleSearch(value) {
                this.emailList = !value || value.indexOf('@') >= 0 ? [] : [
                    value + '@hobot.cc',
                    value + '@163.com',
                    value + '@qq.com',
                ];
            },
            handleAddSubmit() {
                this.$refs['addAccountInfoForm'].validate(valid => {
                    if (valid) {
                        let data  = Utils.deepCopy(this.accountInfo.add)
                        data.acc_pwd = MD5(data.acc_pwd)
                        ME.addOrUpdateAccount(Constants.URL_ADD_ACCOUNT,data).then(json => {
                            if (json.code == 0) {
                                this.$Message.success('添加成功')
                                this.loadTableData()
                                this.hideAddAccountModal()
                            }
                        })
                    } else {
                        this.$Message.error('请检查表单')
                    }
                })
            },
            handleUpdateSubmit(){
                this.$refs['updateAccountInfoForm'].validate(valid => {
                    if (valid) {
                        let data  = Utils.deepCopy(this.accountInfo.update)
                        data.acc_pwd = MD5(data.acc_pwd)
                        ME.addOrUpdateAccount(Constants.URL_UPDATE_ACCOUNT,data).then(json => {
                            if (json.code == 0) {
                                this.$Message.success('更新成功')
                                this.loadTableData()
                                this.hideUpdateAccountModal()
                            }
                        })
                    } else {
                        this.$Message.error('请检查表单')
                    }
                })
            },
            handleResetSubmit(){
                this.$refs['resetPwdForm'].validate(valid => {
                    if (valid) {
                        let data  = Utils.deepCopy(this.accountInfo.resetPwd)
                        data.user_pwd = MD5(data.user_pwd)
                        ME.addOrUpdateAccount(Constants.URL_RESET_PASSWORD,data).then(json => {
                            if (json.code == 0) {
                                this.$Message.success('重置成功')
                                this.hideResetPwdModal()
                            }
                        })
                    } else {
                        this.$Message.error('请检查表单')
                    }
                })
            },
            showAddAccountModal() {
                this.addAccountModal = true
            },
            showUpdateAccountModal(value){
                this.accountInfo.update.acc_role = value.acc_role+""
                this.accountInfo.update.acc_id = value.acc_id
                this.accountInfo.update.acc_name = value.acc_name
                this.accountInfo.update.acc_email = value.acc_email
                this.updateAccountModal = true
            },
            showResetPwdModal(value){
                this.resetPwdTitle  = value.acc_name.trim() || value.acc_id
                this.accountInfo.resetPwd.user_acc = value.acc_id
                this.resetPwdModal = true
            },
            hideAddAccountModal() {
                setTimeout(() => {
                    this.$refs["addAccountInfoForm"].resetFields()
                    this.acc_pwd_check=""
                }, 500)
                this.addAccountModal = false
            },
            hideUpdateAccountModal(){
                setTimeout(() => {
                    this.$refs["updateAccountInfoForm"].resetFields()
                }, 500)
                this.updateAccountModal = false
            },
            hideResetPwdModal(){
                setTimeout(() => {
                    this.$refs["resetPwdForm"].resetFields()
                    this.acc_pwd_check=""
                }, 500)
                this.resetPwdModal = false
            },
            loadTableData(){
                ME.getAllAccount().then(json=>{
                    if(json.code == 0){
                        this.accountData = json.data
                    }
                });
            },
            deleteAccount(data){
                let account = data.acc_id
                let name = data.acc_name || data.acc_id
                this.$Modal.confirm({
                    title: "确认",
                    content: "删除账号【" + name + "】？",
                    onOk: () => {
                        // 先删除特征
                        ME.deleteAccount({acc_id: account}).then(res => {
                            if(res.code == 0){
                                this.$Message.info("删除成功")
                                this.loadTableData()
                            }
                        });
                    }
                });
            }
        },

    }
</script>
